package com.design_mode;

/**
 * Created by dustaple on 2014/7/30.
 */
//饿汉模式
@ThreadSafe
public  class SingletonPattern {
    private static SingletonPattern instance;

    static {
        instance = new SingletonPattern();
    }

    private SingletonPattern() {

    }

    public static SingletonPattern getInstance() {
        return instance;
    }
}

//懒汉模式
@ThreadNotSafe
 class Singleton2 {
    private static Singleton2 instance = null;

    private Singleton2() {

    }

    public static Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}


/*
* 懒汉模式
* synchronized 加锁，保证线程安全
* 每一次都要进入同步区，进行判断空，效率低下
* */
@ThreadSafe
 class Singleton3 {
    private static Singleton3 instance = null;

    private Singleton3() {

    }

    public static Singleton3 getInstance() {
        synchronized (SingletonPattern.class) {
            if (instance == null) {
                instance = new Singleton3();
            }
        }
        return instance;
    }
}

/*
* 懒汉模式
* synchronized 加锁，保证线程安全
* 与上面一种方式相比，只会进入同步区一次，效率高
* */
@ThreadSafe
 class Singleton4 {
    private static Singleton4 instance = null;

    private Singleton4() {

    }

    public static Singleton4 getInstance() {
        if (instance == null) {
            synchronized (SingletonPattern.class) {
                if (instance == null) {
                    instance = new Singleton4();
                }
            }
        }
        return instance;
    }
}

/*
* 懒汉模式
* 静态内部类，内部类的加载时线程安全的
* */
@ThreadSafe
 class Singleton5 {
    private Singleton5() {

    }
    private static final class InnerClass {
        static Singleton5 instance = new Singleton5();
    }

    public static Singleton5 getInstance() {
        return InnerClass.instance;
    }
}

/*
* 枚举实现
* 饿汉模式
* */
@ThreadSafe
enum  Singleton6 {
   SINGLETON_6
}